// frontend/src/admin/CheckinManagement.js

import React, { useState, useEffect, useCallback } from 'react';
import { Table, Button, Modal, Form, Input, Select, DatePicker, message, Space, Tag } from 'antd';
import { adminAPI } from '../services/api';
import moment from 'moment';
import { Link } from 'react-router-dom';

const { Option } = Select;

const CheckinManagement = () => {
  const [form] = Form.useForm();
  const [checkins, setCheckins] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [isModalVisible, setIsModalVisible] = useState(false); // For Add Checkin Modal
  const [guests, setGuests] = useState([]);
  const [rooms, setRooms] = useState([]);
  const [filterParams, setFilterParams] = useState({});

  // New states for custom checkout confirmation modal
  const [isCheckoutConfirmModalVisible, setIsCheckoutConfirmModalModalVisible] = useState(false);
  const [checkoutTargetCheckinId, setCheckoutTargetCheckinId] = useState(null);


  // Destructure pagination and filterParams properties for useCallback dependencies
  const { current, pageSize } = pagination;
  const { id_card, guest_name, room_number, status, startDate, endDate } = filterParams;


  const fetchCheckins = useCallback(async () => {
    setLoading(true);
    try {
      const params = {
        id_card,
        guest_name,
        room_number,
        status,
        startDate,
        endDate,
        limit: pageSize,
        offset: (current - 1) * pageSize,
      };
      const response = await adminAPI.getAllCheckins(params);
      setCheckins(response.data.data || []);
      setPagination(prev => ({ ...prev, total: response.data.total }));
    } catch (error) {
      message.error('获取入住记录失败: ' + (error.response?.data?.message || error.message));
      console.error('Error fetching checkins:', error);
    } finally {
      setLoading(false);
    }
  }, [id_card, guest_name, room_number, status, startDate, endDate, current, pageSize]);


  const fetchGuests = useCallback(async () => {
    try {
      const response = await adminAPI.getAllGuests();
      setGuests(response.data || []);
    } catch (error) {
      message.error('获取客户列表失败: ' + (error.response?.data?.message || error.message));
      console.error('Error fetching guests:', error);
    }
  }, []);

  const fetchRooms = useCallback(async () => {
    try {
      const response = await adminAPI.getAvailableRooms();
      setRooms(Array.isArray(response.data) ? response.data : []);
    } catch (error) {
      message.error('获取可用房间列表失败: ' + (error.response?.data?.message || error.message));
      console.error('Error fetching available rooms:', error);
    }
  }, []);

  useEffect(() => {
    fetchCheckins();
    fetchGuests();
    fetchRooms();
  }, [fetchCheckins, fetchGuests, fetchRooms]);


  const handleTableChange = (newPagination) => {
    if (newPagination.current !== pagination.current || newPagination.pageSize !== pagination.pageSize) {
      setPagination(newPagination);
    }
  };

  const showModal = () => { // For Add Checkin Modal
    form.resetFields();
    form.setFieldsValue({
      check_in_time: moment()
    });
    setIsModalVisible(true);
  };

  const handleCancel = () => { // For Add Checkin Modal
    setIsModalVisible(false);
  };

  const onFinish = async (values) => { // For Add Checkin
    try {
      const formattedValues = {
        ...values,
        checkin_date: values.check_in_time ? values.check_in_time.format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm:ss'),
      };

      await adminAPI.createCheckin(formattedValues);
      message.success('入住办理成功');
      form.resetFields();
      setIsModalVisible(false);
      fetchCheckins();
      fetchRooms();
    } catch (error) {
      message.error('办理入住失败: ' + (error.response?.data?.message || error.message));
      console.error('Error creating checkin:', error);
    }
  };

  // Function to show the custom checkout confirmation modal
  const showCheckoutConfirmModal = (checkinId) => {
    console.log(`[Frontend Debug CM] Checkout button clicked for checkinId: ${checkinId}`); // Debug log 1
    setCheckoutTargetCheckinId(checkinId);
    setIsCheckoutConfirmModalModalVisible(true);
  };

  // Function to handle confirmation from the custom modal
  const handleConfirmCheckout = async () => {
    const checkinId = checkoutTargetCheckinId;
    console.log(`[Frontend Debug CM] Custom Modal confirmed for checkinId: ${checkinId}`); // Debug log 2
    setLoading(true); // Set loading for the checkout action
    try {
      const checkoutTime = moment().format('YYYY-MM-DD HH:mm:ss');
      console.log(`[Frontend Debug CM] Preparing to send checkout request for checkinId: ${checkinId} with checkoutTime: ${checkoutTime}`); // Debug log 3
      await adminAPI.checkoutGuest(checkinId, { check_out_time: checkoutTime });
      message.success('退房成功');
      console.log(`[Frontend Debug CM] Checkout request succeeded for checkinId: ${checkinId}`); // Debug log 4
      setIsCheckoutConfirmModalModalVisible(false); // Close the modal
      setCheckoutTargetCheckinId(null); // Clear target ID
      fetchCheckins(); // Refresh checkin list
      fetchRooms(); // Refresh available rooms
    } catch (error) {
      console.error(`[Frontend Debug CM] Error during checkout for checkinId: ${checkinId}:`, error); // Debug log 5
      message.error('退房失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setLoading(false); // Reset loading
      console.log(`[Frontend Debug CM] Checkout attempt finished for checkinId: ${checkinId}`); // Debug log 6
    }
  };

  // Function to cancel from the custom modal
  const handleCancelCheckoutConfirmModal = () => {
    console.log(`[Frontend Debug CM] Custom Modal cancelled for checkinId: ${checkoutTargetCheckinId}`); // Debug log 7
    setIsCheckoutConfirmModalModalVisible(false);
    setCheckoutTargetCheckinId(null);
  };


  const onSearch = (values) => {
    const newFilterParams = {
      id_card: values.id_card || undefined,
      guest_name: values.guest_name || undefined,
      room_number: values.room_number || undefined,
      status: values.status || undefined,
      startDate: values.dateRange && values.dateRange[0] ? values.dateRange[0].format('YYYY-MM-DD') : undefined,
      endDate: values.dateRange && values.dateRange[1] ? values.dateRange[1].format('YYYY-MM-DD') : undefined,
    };
    setFilterParams(newFilterParams);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const columns = [
    { title: '入住单号', dataIndex: 'checkin_id', key: 'checkin_id' },
    { title: '房间号', dataIndex: 'room_number', key: 'room_number' },
    { title: '客户姓名', dataIndex: 'guest_name', key: 'guest_name' },
    { title: '身份证号', dataIndex: 'id_card', key: 'id_card' },
    { title: '房间类型', dataIndex: 'room_type', key: 'room_type' },
    { title: '房间单价(¥/天)', dataIndex: 'room_price', key: 'room_price', render: price => `¥${parseFloat(price).toFixed(2)}` },
    {
      title: '入住时间',
      dataIndex: 'checkin_date',
      key: 'checkin_date',
      render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '',
    },
    {
      title: '退房时间',
      dataIndex: 'checkout_date',
      key: 'checkout_date',
      render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '',
    },
    { title: '总金额(¥)', dataIndex: 'total_amount', key: 'total_amount', render: (text) => text !== null ? `¥${parseFloat(text).toFixed(2)}` : 'N/A' },
    {
      title: '状态', dataIndex: 'status', key: 'status',
      render: status => {
        let color = '';
        if (status === '入住中') color = 'blue';
        else if (status === '已退房') color = 'green';
        return <Tag color={color}>{status}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
          <Space size="small">
            {record.status === '入住中' && (
                <Button type="primary" onClick={() => showCheckoutConfirmModal(record.checkin_id)} danger size="small">
                  退房
                </Button>
            )}
            <Link to={`/admin/checkins/${record.checkin_id}`}>
              <Button size="small">详情</Button>
            </Link>
          </Space>
      ),
    },
  ];

  return (
      <div style={{ padding: 24 }}>
        <h2>入住管理</h2>
        <Form layout="inline" onFinish={onSearch} style={{ marginBottom: 16 }}>
          <Form.Item name="id_card" label="身份证号">
            <Input placeholder="客户身份证号" />
          </Form.Item>
          <Form.Item name="guest_name" label="客户姓名">
            <Input placeholder="客户姓名" />
          </Form.Item>
          <Form.Item name="room_number" label="房间号">
            <Input placeholder="输入房间号" />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
              <Option value="入住中">入住中</Option>
              <Option value="已退房">已退房</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="入住/退房日期">
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={showModal}>
              办理入住
            </Button>
          </Form.Item>
        </Form>

        <Table
            columns={columns}
            dataSource={checkins}
            rowKey="checkin_id"
            loading={loading}
            pagination={pagination}
            onChange={handleTableChange}
            variant="bordered" /* Removed inline comment */
            locale={{ emptyText: '暂无入住记录' }}
        />

        <Modal
            title="办理入住"
            open={isModalVisible}
            onCancel={handleCancel}
            footer={null}
            destroyOnHidden={true} /* Removed inline comment */
        >
          <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
          >
            <Form.Item
                name="guest_id"
                label="选择客户"
                rules={[{ required: true, message: '请选择客户' }]}
            >
              <Select
                  showSearch
                  placeholder="选择客户 (姓名 - 身份证号)"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                      String(option.children || '').toLowerCase().includes(input.toLowerCase())
                  }
              >
                {guests.map(guest => (
                    <Option key={guest.guest_id} value={guest.guest_id}>
                      {guest.name} - {guest.id_card}
                    </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
                name="room_id"
                label="选择房间"
                rules={[{ required: true, message: '请选择房间' }]}
            >
              <Select
                  showSearch
                  placeholder="选择房间 (房间号 - 价格)"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                      String(option.children || '').toLowerCase().includes(input.toLowerCase())
                  }
              >
                {rooms.map(room => (
                    <Option key={room.room_id} value={room.room_id}>
                      {room.room_number} - ¥{parseFloat(room.price).toFixed(2)}
                    </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
                name="check_in_time"
                label="入住时间"
                rules={[{ required: true, message: '请选择入住时间' }]}
            >
              <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                办理入住
              </Button>
              <Button onClick={handleCancel} style={{ marginLeft: 8 }}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        {/* Custom Checkout Confirmation Modal */}
        <Modal
            title="确认退房"
            open={isCheckoutConfirmModalVisible}
            onOk={handleConfirmCheckout}
            onCancel={handleCancelCheckoutConfirmModal}
            okText="确定"
            cancelText="取消"
            confirmLoading={loading}
            destroyOnHidden={true} /* Removed inline comment */
        >
          <p>您确定要为该入住记录办理退房吗？退房后将无法再添加消费。</p>
        </Modal>
      </div>
  );
};

export default CheckinManagement;
